import websocket
import threading, time


def on_close(ws):
    '''
        - websocket client 重试机制
    '''
    print("Retry : %s" % time.ctime())
    time.sleep(2)
    connect_websocket()  # 每2s 重试一次


def on_open(ws):
    '''
        - 当系统连接上后的提示
    '''
    print('connection established')


def on_message(wsapp, message):
    '''
        - 接收服务器websocket 发送来的消息
    '''
    print(message)


def connect_websocket():
    '''
        - 尝试连接websocket 服务器
        - 并给该线程设置守护
    '''
    ws = websocket.WebSocketApp(
        "ws://127.0.0.1:8888/ws/2323",
        on_open=on_open,
        on_close=on_close,
        cookie="chocolate",
        on_message=on_message
    )
    wst = threading.Thread(target=ws.run_forever)
    wst.daemon = True
    wst.start()


def run():
    '''
        - websocket 组件会跟随fastapi 主进程启动
        - 客户端系统会每隔2s 尝试一次连接
    '''
try:
    connect_websocket()
except Exception as err:
    print(err)
    print("connect failed")
